package com.models.shiro;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.modules.utils.EncryptUtils;
import com.wxp.entity.Resource;
import com.wxp.entity.User;
import com.wxp.service.ResourceService;
import com.wxp.service.UserService;

public class JdbcShiroRealm extends AuthorizingRealm{
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private ResourceService resourceService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
	    //User userInfo  = (User)principals.getPrimaryPrincipal();
		//获取所有权限
		List<Resource> list = resourceService.findAll();
		for(Resource resource :list){
			if(StringUtils.isNotBlank(resource.getPermission())){
				authorizationInfo.addStringPermission(resource.getPermission());
			}
		}
	    return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String)token.getPrincipal();
		User user = userService.getByNameCode(username);
		if(user == null){
	        return null;
	    }
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				user.getUserId(),  user.getPassword(),ByteSource.Util.bytes(EncryptUtils.base+user.getSalt()),getName());
		return authenticationInfo;
	}
	
	
	 
	
}
